<?php
/**
 * File:loginControl.php
 * @author: CIS505 TEAM 1
 * @version: 2012-11-29
 * Purpose: login authentication
 */
require_once("util.php");
require_once("loginView.php");

/**
 * User Login
 */
function login( )
{
  $userName = "";
  $password = "";

  if (isset($_POST['submitBttn'])) {
    $userName = sanitize($_POST['userName']);
    $password = sanitize($_POST['password']);
    authenticateLogin($userName, $password);
  }
}

function authenticateLogin($userName, $password)
{
  // $row[0]: userId
  // $row[1]: foreName
  // $row[2]: sureName
  // $row[3]: userName
  // $row[4]: email
  // $row[5]: password
  // $row[6]: token

  $conn = connect( );
  $query = "SELECT * FROM user WHERE userName = '$userName'";
  $result = mysqli_query($conn, $query);

  if ($result == false) {
    exit("Database error: $query<br />" . mysqli_error($conn));
  }

  elseif (mysqli_num_rows($result)) {
    $row = mysqli_fetch_row($result);
    $salt1 = "qm&h*";
    $salt2 = "pg!@";
    $token = sha1("$salt1$password$salt2");
    $userID = $row[0];

    if ($token == $row[6]) {
      session_start();
      $_SESSION['userID'] = $row[0];
      $_SESSION['userName'] = $row[3];

      $userID = $_SESSION['userID'];
      $userName = $_SESSION['userName'];

      exit(header("LOCATION:php/control.php"));
    }

    else {
      exit("Invalid username/password combination");

    }
  mysqli_close($conn);
  }
}

?>